package com.proj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GameList {
    private static List<Game>gameList=new ArrayList<Game>();
    private static int num=0;
    public static String add(User user){
        String gameId="";
        Game game=null;
        int state=-1;
        if(!gameList.isEmpty()){
            game=gameList.get(gameList.size()-1);
            state=game.addUser(user);
        }
        if(game==null||state==3){
            Game newGame=new Game();
            newGame.setId(String.valueOf(gameList.size()));//分配gameId
            gameId=newGame.getId();
            newGame.addUser(user);
            gameList.add(newGame);
        }else{
            gameId=game.getId();
        }
        return gameId;
    }
    public static Game getGameById(String id){
        Game game=null;
        for(int i=0;i<gameList.size();i++){
            game=gameList.get(i);
            if(game.getId().equals(id)){
                break;
            }
        }
        return game;
    }
    public static void cancelMatch(String userName){
        Game game=null;
        int state=-1;
        if(!gameList.isEmpty()){
            game=gameList.get(gameList.size()-1);
            state=game.getState();
        }
        if(state==1){
            if(game.isInGame(userName))
                gameList.remove(gameList.size()-1);
        }else{
            System.out.println("cancelMatch wrong:"+userName);
        }
    }
    public static void quitGame(String userName){
        Game game=null;
        for(int i=0;i<gameList.size();i++){
            game=gameList.get(i);
            if(game.isInGame(userName)){
                game.removeUser(userName);
            }
        }
    }
}
